import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hkzf_flutter/dio/general_type.dart';
import 'package:hkzf_flutter/pages/search/filter_bar/data.dart';
import 'package:hkzf_flutter/pages/search/filter_bar/item.dart';
import 'package:hkzf_flutter/scoped_model/filter_bar_model.dart';
import 'package:hkzf_flutter/utils/common_picker/index.dart';
import 'package:hkzf_flutter/utils/dio_http.dart';
import 'package:hkzf_flutter/utils/scoped_model_helper.dart';
// 城市id缓存值
String? cityIdCache;

class FilterBar extends StatefulWidget {
  final ValueChanged<FilterBarResult> onChange;// 改变回调
  const FilterBar({super.key, required this.onChange});

  @override
  State<FilterBar> createState() => _FilterBarState();
}

class _FilterBarState extends State<FilterBar> {
  bool isAreaActive = false;//  区域是否激活
  bool isRentTypeActive = false;//  出租方式是否激活
  bool isPriceActive = false;//  租金是否激活
  bool isFilterActive = false;//  更多筛选是否激活

  String areaId = 'null';//  区域Id
  String rentTypeId = 'null';//  出租方式Id
  String priceId = 'null';//  租金Id
  List<String> moreIds = [];// 更多筛选Id
  
    // 通用类型数据集
  List<GeneralType> areaList = [// 区域数据集
   
  ];
  List<GeneralType> priceList = [// 租金式数据集
    
  ];
  List<GeneralType> rentTypeList = [// 出租方式数据集
   
  ];
  List<GeneralType> roomTypeList = [// 户型数据集
 
  ];
  List<GeneralType> orientedList = [// 朝向数据集
   
  ];
  List<GeneralType> floorList = [// 楼层数据集
    
  ];

  // 区域选择回调
  _onAreaChange(context) {
    setState(() {
      //  区域激活
      isAreaActive = true;
    });
    var result = CommonPicker.showPicker(
      context: context,
      // .whereType<String>() 过滤掉可能为 null 的值，确保生成的列表为 List<String> 类型
      options: areaList.map((item) => item.name).whereType<String>().toList(),
      value: 0,
    );
    result.then((index) {// 用户完成选择后，会触发这个回调函数
      print('选择后的索引:$index');
      if (index == null) return;
      setState(() {
        areaId = areaList[index].id!;
      });
      _onChange();
    }).whenComplete(() {// 用于在异步操作完成时，执行某些操
      print('完成选择直接操作');
      setState(() {
        isAreaActive = false;
      });
    });
  }
  // 出租方式选择回调
  _onRentTypeChange(context) {
    setState(() {
      isRentTypeActive = true;
    });
    var result = CommonPicker.showPicker(
      context: context,
      options: rentTypeList.map((item) => item.name).whereType<String>().toList(),
      value: 0,
    );
    result.then((index) {
      if (index == null) return;
      setState(() {
        rentTypeId = rentTypeList[index].id!;
      });
      _onChange();
    }).whenComplete(() {
      setState(() {
        isRentTypeActive = false;
      });
    });
  }
  // 租金选择回调
  _onPriceChange(context) {
    setState(() {
      isPriceActive = true;
    });
    var result = CommonPicker.showPicker(
      context: context,
      options: priceList.map((item) => item.name).whereType<String>().toList(),
      value: 0,
    );
    result.then((index) {
      if (index == null) return;
      setState(() {
        priceId = priceList[index].id!;
      });
      _onChange();
    }).whenComplete(() {
      setState(() {
        isPriceActive = false;
      });
    });
  }
  // 更多筛选项点击回调
  _onFilterChange(context) {
    // 打开更多筛选器抽屉
    Scaffold.of(context).openEndDrawer();
  }

   _onChange() {// 筛选器改变回调
    var selectedList = ScopedModelHelper.getModel<FilterBarModel>(context).selectedList;
    if (widget.onChange != null) {
      widget.onChange(
        FilterBarResult(
          areaId: areaId,
          priceId: priceId,
          rentTypeId: rentTypeId,
          moreIds: selectedList.toList(),
        ),
      );
    }
  }
  // 初始化设置数据
  _getData() async{
    // 获取选中的城市id
    var cityId = ScopedModelHelper.getAreaId(context);
    // 更新缓存城市id
    cityIdCache = cityId;
    // 发送请求
    var path = '/houses/condition?id=$cityId';
    var res =await DioHttp.of(context).get(path);
    var data = json.decode(res.toString())['body'];
    List<GeneralType> areaList = (data['area']['children'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> priceList = (data['price'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> rentTypeList =  (data['rentType'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> roomTypeList = (data['roomType'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> orientedList = (data['oriented'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> floorList =(data['floor'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    if (mounted) { // 添加 mounted 判断，确保组件仍挂载
      // 确保只在组件处于挂载状态时才进行状态更新
      setState(() {
        this.areaList = areaList;
        this.priceList = priceList;
        this.rentTypeList = rentTypeList;
        this.roomTypeList = roomTypeList;
        this.orientedList = orientedList;
        this.floorList = floorList;
      });
    }
    Map<String, List<GeneralType>> dataList = Map<String, List<GeneralType>>();
    dataList['roomTypeList'] = roomTypeList;
    dataList['orientedList'] = orientedList;
    dataList['floorList'] = floorList;
    ScopedModelHelper.getModel<FilterBarModel>(context).dataList = dataList;
  }

  @override
  void initState() {
    // 确保在 UI 完成构建后再进行某些操作（如数据加载）
    WidgetsBinding.instance.addPostFrameCallback((_) {
       _getData();
    });
    super.initState();
  }
  @override
  // 监听跨层级，全局依赖的变化
  void didChangeDependencies() {
    if(cityIdCache!=null && cityIdCache != ScopedModelHelper.getAreaId(context)){
      // 重新更新筛选数据
      _getData();
    }
    _onChange();
    super.didChangeDependencies();
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      height: 41.0,
      decoration: const BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.black12,width: 1.0))
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FilterBarItem(
            title: areaList.firstWhere((item) => item.id == areaId,orElse: () => GeneralType('区域', ''),).name ?? '区域',
            isActive: isAreaActive,
            onTap: _onAreaChange,
          ),
          FilterBarItem(
            title: rentTypeList.firstWhere((item) => item.id == rentTypeId,orElse: () => GeneralType('方式', ''),).name ?? '方式',
            isActive: isRentTypeActive,
            onTap: _onRentTypeChange,
          ),
          FilterBarItem(
            title:  priceList.firstWhere((item) => item.id == priceId,orElse: () => GeneralType('租金', ''),).name ?? '租金',
            isActive: isPriceActive,
            onTap: _onPriceChange,
          ),
          FilterBarItem(
            title: '筛选',
            isActive: isFilterActive,
            onTap: _onFilterChange,
          ),
        ],
      ),
    );
  }
}
